package core

import (
	"data-transfer/conf"
	"data-transfer/global"
	"data-transfer/utils"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"log"
	"os"
	"time"
)

var level zapcore.Level
var myZap *conf.Zap

func initZap() {
	zLevel := global.GViper.GetString("zap.level")
	format := global.GViper.GetString("zap.format")
	prefix := global.GViper.GetString("zap.prefix")
	director := global.GViper.GetString("zap.director")
	linkName := global.GViper.GetString("zap.link-name")
	showLine := global.GViper.GetBool("zap.showLine")
	encodeLevel := global.GViper.GetString("zap.encode-level")
	stacktraceKey := global.GViper.GetString("zap.stacktrace-key")
	logInConsole := global.GViper.GetBool("zap.log-in-console")

	myZap = &conf.Zap{
		Level:         zLevel,
		Format:        format,
		Prefix:        prefix,
		Director:      director,
		LinkName:      linkName,
		ShowLine:      showLine,
		EncodeLevel:   encodeLevel,
		StacktraceKey: stacktraceKey,
		LogInConsole:  logInConsole,
	}
}
func Zap() (logger *zap.Logger) {

	initZap() //初始化

	if ok, _ := utils.PathExists(myZap.Director); !ok { //判断是否指定文件夹
		log.Printf("create %v dirctory\n", myZap.Director)
		_ = os.Mkdir(myZap.Director, os.ModePerm)
	}

	switch myZap.Level {
	case "debug":
		level = zap.DebugLevel
	case "info":
		level = zap.InfoLevel
	case "warn":
		level = zap.WarnLevel
	case "error":
		level = zap.ErrorLevel
	case "dpanic":
		level = zap.DPanicLevel
	case "panic":
		level = zap.PanicLevel
	case "fatal":
		level = zap.FatalLevel
	default:
		level = zap.InfoLevel
	}

	if level == zap.DebugLevel || level == zap.ErrorLevel {
		logger = zap.New(getEncoderCore(), zap.AddStacktrace(level))
	} else {
		logger = zap.New(getEncoderCore())
	}
	if myZap.ShowLine {
		logger = logger.WithOptions(zap.AddCaller())
	}
	return logger
}

// getEncoderConfig 获取 zapcore.EncoderConfig
func getEncoderConfig() (config zapcore.EncoderConfig) {
	config = zapcore.EncoderConfig{
		MessageKey:     "message",
		LevelKey:       "level",
		TimeKey:        "time",
		NameKey:        "logger",
		CallerKey:      "caller",
		StacktraceKey:  myZap.StacktraceKey,
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     CustomTimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.FullCallerEncoder,
	}
	switch {
	case myZap.EncodeLevel == "LowercaseLevelEncoder": //小写编码器（默认）
		config.EncodeLevel = zapcore.LowercaseLevelEncoder
	case myZap.EncodeLevel == "LowercaseColorLevelEncoder": //小写编码器带颜色
		config.EncodeLevel = zapcore.LowercaseColorLevelEncoder
	case myZap.EncodeLevel == "CapitalLevelEncoder": //大写编码器
		config.EncodeLevel = zapcore.CapitalLevelEncoder
	case myZap.EncodeLevel == "CapitalColorLevelEncoder": //大写编码器带颜色
		config.EncodeLevel = zapcore.CapitalColorLevelEncoder
	default:
		config.EncodeLevel = zapcore.LowercaseLevelEncoder
	}
	return config
}

func getEncoderCore() (core zapcore.Core) {
	writer, err := utils.GetWriteSyncer(myZap) //使用file-rotatelogs进行日志分割
	if err != nil {
		log.Printf("Get Write Syncer Failed err:%v", err.Error())
		return
	}
	return zapcore.NewCore(getEncoder(), writer, level)
}

//getEncoder 获取zapcore.Encoder
func getEncoder() zapcore.Encoder {
	if myZap.Format == "json" {
		return zapcore.NewJSONEncoder(getEncoderConfig())
	}
	return zapcore.NewConsoleEncoder(getEncoderConfig())
}

//CustomTimeEncoder 自定义日志输出时间格式
func CustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
	enc.AppendString(t.Format(myZap.Prefix + "2006/01/02 - 15:04:05.000"))
}
